﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FigKey_TestExec_SL.Entity;
using FigKey_TestExec_SL.Common;
using System.Drawing;
using Test_Operator_Platform.Common;

namespace Test_Operator_Platform.Test
{
    class UpdateUI
    {
        /// <summary>
        /// 主线程控制显示
        /// </summary>
        public static void UpdateTestUI(TestRecordData tData, DataGridView view)
        {
            if (tData.TResult.TestData.Count <= 0)
                return;
            if (tData.IsMulThread)
            {
                UpdateMTestRecord(view, tData.TestHisData, tData.TResult);
            }
            else
            {
                UpdateTestRecord(view, tData.TestHisData, tData.TResult);
            }
        }

        /// <summary>
        /// 多线程任务完成后显示所有-缺陷-任务多了可能会等待时间略长
        /// </summary>
        /// <param name="dview"></param>
        /// <param name="tResult"></param>
        public static void UpdateTestRecord1(DataGridView dview, TestResult tResult)
        {
            if (tResult.TestData.Count <= 0)
                return;
            //将失败项显示到最后
            TestHistory failItem = null;
            foreach (var tHis in tResult.TestData)
            {
                if (tHis.ShowStatus)
                    continue;
                if (!tHis.LimitExist)
                    continue;
                if (tHis.TestResult != "FAIL")
                {
                    QueryAddTest(dview, tHis);
                    tHis.ShowStatus = true;
                }
                else
                {
                    failItem = tHis;
                }
            }
            if (failItem != null)
            {
                QueryAddTest(dview, failItem);
                failItem.ShowStatus = true;
            }
        }

        public static void UpdateTestRecord(DataGridView dview, TestHistory tHis, TestResult tResult)
        {
            var results = tResult.TestData.FindAll(p => p.TestNumber == tHis.TestNumber && p.TestItem == tHis.TestItem);
            foreach (var rHis in results)
            {
                var index = QueryAddTest(dview, rHis);
                //if (index < 0)
                //    continue;
                //UpdateDataViewTest(dview, index, rHis.TestResult, rHis.TestValues);
            }
        }

        /// <summary>
        /// 多线程任务，查询实时显示
        /// </summary>
        /// <param name="dview"></param>
        /// <param name="tResult"></param>
        public static void UpdateMTestRecord(DataGridView dview, TestHistory cHis, TestResult tResult)
        {
            if (tResult.TestData.Count <= 0)
                return;
            //将失败项显示到最后
            if (cHis == null)//查询失败项
            {
                foreach (var tHis in tResult.TestData)
                {
                    if (tHis.ShowStatus)
                        continue;
                    if (!tHis.LimitExist)
                        continue;
                    if (tHis.TestResult == "FAIL")
                    {
                        QueryAddTest(dview, tHis);
                        tHis.ShowStatus = true;
                    }
                }
                return;
            }

            var result = tResult.TestData.FindAll(p => p.TestItem == cHis.TestItem);
            foreach (var tHis in result)
            {
                if (tHis.ShowStatus)
                    continue;
                if (!tHis.LimitExist)
                    continue;
                if (tHis.TestResult != "FAIL")
                {
                    QueryAddTest(dview, tHis);
                    tHis.ShowStatus = true;
                }
            }
        }

        public static int QueryAddTest(DataGridView dview, TestHistory tHis)
        {
            int dIndex = -1;
            string testSequence = "0";
            if (dview != null)
            {
                testSequence = DataViewUtils.GetTestSequence();
                if (testSequence == "1")//显示所有序列
                {
                    //SendMessage(MessageType.MessageInfo, $"{testResult.TestHistory.TestItem} Testing", Color.Green);
                    dview.Invoke(new Action(() => { dIndex = AddTestRow(dview, tHis.TestItem, tHis.TestAction, tHis.Limit); }));
                }
                else
                {
                    if (tHis.Sequence == "Main")//只显示Main序列
                    {
                        //查询匹配行
                        if (tHis.Limit != null)
                        {
                            //SendMessage($"{tHis.TestItem} Testing", Color.Green);
                        }
                        dview.Invoke(new Action(() => { dIndex = AddTestRow(dview, tHis.TestItem, tHis.TestAction, tHis.Limit); }));
                        //dIndex = QueryGridViewRow(dview, tHis.TestItem, actions[a].Action);
                    }
                    else if (tHis.Sequence == "Exception")
                    {
                        //SendMessage($"Start checking the tests, Please Wait...", Color.Green);
                    }
                    else if (tHis.Sequence == "AfterMain")
                    {
                        //SendMessage($"Please wait AfterMain to complete", Color.Green);
                    }
                }

                if (dIndex == -1)
                    return -1;
                dview.Invoke(new Action(() =>
                {
                    if (tHis.TestStatus == FigKey_TestExec_SL.FkEnum.TestPlanStatus.Pass)
                    {
                        dview.Rows[dIndex].DefaultCellStyle.BackColor = Color.Lime;
                        dview.Rows[dIndex].Cells[6].Value = tHis.TestValues;
                        dview.Rows[dIndex].Cells[7].Value = "PASS";
                    }
                    else if (tHis.TestStatus == FigKey_TestExec_SL.FkEnum.TestPlanStatus.Fail)
                    {
                        dview.Rows[dIndex].DefaultCellStyle.BackColor = Color.Red;
                        dview.Rows[dIndex].Cells[6].Value = tHis.TestValues;
                        dview.Rows[dIndex].Cells[7].Value = "FAIL";
                    }
                    WinLibrary.DataViewManager.DataViewUtils.SetGridViewSelected(dview, dIndex);//设置选中
                }));
            }
            return dIndex;
        }

        public static int AddTestRow(DataGridView view, string testItem, string action, ActionLimit limit)
        {
            if (limit == null)
                return -1;
            if (ShowSequenceByLimit())
            {
                if (limit == null)
                    return -1;
            }
            if (QueryGridViewRow(view, testItem, action) != -1)
            {
                return -1;
            }
            int index = view.Rows.Add();
            view.Rows[index].Cells[0].Value = index + 1;
            view.Rows[index].Cells[1].Value = testItem;
            view.Rows[index].Cells[2].Value = action;

            if (limit != null)
            {
                switch (limit.LimitKind)
                {
                    case "最小值/最大值":
                        {
                            if (limit.Minimum != null)
                                view.Rows[index].Cells[3].Value = limit.Minimum;
                            if (limit.Maximum != null)
                                view.Rows[index].Cells[4].Value = limit.Maximum;
                            break;
                        }
                    case "相等":
                        {
                            if (limit.Equivalence != null)
                                view.Rows[index].Cells[3].Value = limit.Equivalence;
                            if (limit.Equivalence != null)
                                view.Rows[index].Cells[4].Value = limit.Equivalence;
                            break;
                        }
                    case "公差":
                        {
                            if (limit.Nominal != null)
                            {
                                if (limit.Tolerance != null)
                                {
                                    view.Rows[index].Cells[3].Value = limit.Nominal - limit.Tolerance;
                                    view.Rows[index].Cells[4].Value = limit.Tolerance + limit.Tolerance;
                                }
                                else
                                {
                                    view.Rows[index].Cells[3].Value = limit.Nominal;
                                    view.Rows[index].Cells[4].Value = limit.Tolerance;
                                }
                            }
                            break;
                        }
                }
            }
            return index;
        }

        private static int QueryGridViewRow(DataGridView view, string testItem, string action)
        {
            // Linq模糊查询 
            IEnumerable<DataGridViewRow> enumerableList = view.Rows.Cast<DataGridViewRow>();
            List<DataGridViewRow> list = null;
            list = (from item in enumerableList
                    where item.Cells[1].Value.ToString() == testItem && item.Cells[2].Value.ToString() == action
                    select item).ToList();
            if (list.Count == 1)
            {
                //set selected
                view.Rows[list[0].Index].Selected = true;
                return list[0].Index;
            }
            return -1;
        }

        private static bool ShowSequenceByLimit()
        {
            var limit = System.Configuration.ConfigurationManager.AppSettings["mainSequenceByLimit"];
            if (limit == null)
                return true;//限制LIMIT，只显示LIMIT的测试
            if (limit.ToString() == "1")
                return true;
            return false;
        }
    }
}
